import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:lib_uikit/lib_uikit.dart';
import 'package:lib_uikit/resource/resources.dart';
import 'package:lib_uikit/widgets/gt_dropdown_v3.dart';
import 'package:lib_uikit/widgets/gt_search_view_v3.dart';

class GTDropdownTopPopupWidgetV3 extends StatefulWidget {
  final bool? showInput;
  final String? inputHint;
  final ValueChanged<String>? onSearchSubmit;
  final List<GTDropDownContentModalV3>? list;
  final ValueChanged<GTDropDownContentModalV3>? onItemClicked;
  final Color? popupSelectBackground;
  final String? selectTitle;
  final double? topPopupMaxPercentHeight;
  final String text;
  final Color? textColor;
  final String? tag;
  const GTDropdownTopPopupWidgetV3({
    super.key,
    this.showInput,
    this.inputHint,
    this.onSearchSubmit,
    this.list,
    this.onItemClicked,
    this.popupSelectBackground,
    this.selectTitle,
    this.topPopupMaxPercentHeight,
    this.text = "",
    this.textColor,
    this.tag,
  });

  @override
  State<StatefulWidget> createState() => _DropdownPopupContainerWidgetV3();
}

class _DropdownPopupContainerWidgetV3 extends State<GTDropdownTopPopupWidgetV3> {
  String _searchText = "";
  List<GTDropDownContentModalV3> _filteredList = [];
  String _title = "";
  bool isFirst = true;

  @override
  void initState() {
    super.initState();
    _filteredList = widget.list ?? [];
  }

  @override
  Widget build(BuildContext context) {
    _title = widget.selectTitle ?? "";
    double screenHeight = MediaQuery.of(context).size.height;
    Widget _container() {
      return Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (widget.showInput ?? false) ...[
            const SizedBox(
              height: 8,
            ),
            GTSearchViewV3(
              hint: widget.inputHint ?? "",
              type: GTSearchTypeV3.dropdown,
              onSubmit: (String value) {
                if (value.isNotEmpty) {
                  widget.onSearchSubmit?.call(value);
                }
                //关闭键盘
                WidgetsBinding.instance.addPostFrameCallback((_) {
                  SystemChannels.textInput.invokeMethod('TextInput.hide');
                });
              },
              onTextChanged: (text) {
                setState(() {
                  _searchText = text;
                  _filteredList = (widget.list ?? [])
                      .where((item) => item.title.toLowerCase().contains(text.toLowerCase()))
                      .toList();
                });
              },
            ),
            const SizedBox(
              height: 8,
            )
          ],
          Flexible(
              flex: 1,
              child: _filteredList.isEmpty
                  ? const Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        SizedBox(
                          height: 40,
                        ),
                        GTEmptyViewV3(
                          iconType: GTEmptyIconType.data,
                        ),
                        SizedBox(
                          height: 80,
                        ),
                      ],
                    )
                  : MediaQuery.removePadding(
                      context: context,
                      removeTop: true,
                      removeBottom: true,
                      child: ListView.separated(
                        itemCount: _filteredList.length,
                        physics: const ClampingScrollPhysics(),
                        shrinkWrap: true,
                        separatorBuilder: (context, index) => const SizedBox(height: 8),
                        itemBuilder: (context, index) {
                          final title = _filteredList[index].title;
                          final searchTextIndex =
                              _searchText.isEmpty ? -1 : title.toLowerCase().indexOf(_searchText.toLowerCase());
                          return GestureDetector(
                            onTap: () {
                              SmartDialog.dismiss(tag:widget.tag);
                              setState(() {
                                _title = _filteredList[index].title;
                                isFirst = false;
                              });
                              widget.onItemClicked?.call(_filteredList[index]);
                            },
                            child: Container(
                                padding: const EdgeInsets.symmetric(vertical: 2),
                                decoration: BoxDecoration(
                                  color: _title == _filteredList[index].title
                                      ? GTColorsV3.neutral2.color
                                      : Colors.transparent,
                                  borderRadius: BorderRadius.circular(6),
                                ),
                                height: 36,
                                child: Row(children: <Widget>[
                                  const SizedBox(width: 12),
                                  if (_filteredList[index].imagePath != null) ...[
                                    GTImage(
                                      url: _filteredList[index].imagePath ?? "",
                                      width: 24,
                                      height: 24,
                                      radiusAll: 12,
                                      showPlaceholder: true,
                                      fit: BoxFit.cover,
                                      errorPath: Images.uikitPlaceholder,
                                      placeholderPath: Images.uikitPlaceholder,
                                    ),
                                    const SizedBox(width: 8),
                                  ],
                                  Expanded(
                                    child: searchTextIndex == -1
                                        ? Text(
                                            title,
                                            style: gtTextStyleW500(color: GTColorsV3.text1.color, fontSize: 14),
                                          )
                                        : Text.rich(
                                            TextSpan(
                                              children: [
                                                TextSpan(
                                                  text: title.substring(0, searchTextIndex),
                                                ),
                                                TextSpan(
                                                  text: title.substring(
                                                      searchTextIndex, searchTextIndex + _searchText.length),
                                                  style: gtTextStyleW500(color: GTColorsV3.brand3.color, fontSize: 16),
                                                ),
                                                TextSpan(
                                                  text: title.substring(searchTextIndex + _searchText.length),
                                                ),
                                              ],
                                              style: gtTextStyleW500(color: GTColorsV3.text1.color, fontSize: 16),
                                            ),
                                          ),
                                  ),
                                  if (_filteredList[index].endText != null)
                                    Text(
                                      _filteredList[index].endText ?? "",
                                      style: gtTextStyleW500(color: GTColorsV3.text1.color, fontSize: 14),
                                    ),
                                  const SizedBox(
                                    width: 16,
                                  ),
                                  if (_title == _filteredList[index].title) ...[
                                    Icon(
                                      GTIconFont.e942,
                                      color: GTColorsV3.icon5.color,
                                      size: 16,
                                    ),
                                    const SizedBox(width: 12),
                                  ],
                                ])),
                          );
                        },
                      ),
                    ))
        ],
      );
    }

    Widget child = StatefulBuilder(builder: (context, setState) {
      return ConstrainedBox(
        constraints: BoxConstraints(
          maxHeight: screenHeight * (widget.topPopupMaxPercentHeight ?? 0.8),
        ),
        child: Container(
            padding: const EdgeInsets.only(top: 8, left: 12, right: 12),
            decoration: BoxDecoration(
              color: GTColorsV3.bg1.color,
              borderRadius: const BorderRadius.only(
                bottomLeft: Radius.circular(12),
                bottomRight: Radius.circular(12),
              ),
            ),
            child: _container()),
      );
    });
    return child;
  }
}
